package com.cloud.point.concurrent.general;

import java.util.concurrent.TimeUnit;

import lombok.extern.slf4j.Slf4j;

/**
 * 死锁|活锁的实现
 *
 * @author 24373
 * @version 1.0
 * @date 2024-07-03 22:21
 */
@Slf4j
public class TestDeadLock {

    public static void main(String[] args) throws Exception {

        //test2();
        test3();

    }

    static volatile int count = 10;

    /**
     * 活锁
     */
    private static void test3() {
        new Thread(() -> {
            while (count > 0) {
                try {
                    TimeUnit.MILLISECONDS.sleep(50);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                count--;
                log.info("count--,{}", count);
            }
        }).start();

        new Thread(() -> {
            while (count < 20) {
                try {
                    TimeUnit.MILLISECONDS.sleep(50);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                count++;
                log.info("count++,{}", count);
            }
        }).start();
    }

    /**
     * deadlock
     */
    private static void test2() {
        Object o = new Object();
        Object o2 = new Object();

        new Thread(() -> {
            synchronized (o) {
                log.info("{}获取o", Thread.currentThread().getId());
                synchronized (o2) {
                    log.info("o2");
                }
            }
        }).start();
        new Thread(() -> {
            synchronized (o2) {
                log.info("{}获取o2", Thread.currentThread().getId());
                synchronized (o) {
                    log.info("o");
                }
            }
        }).start();
    }

}
